//
//  FMSNetWorkModule.m
//  WRNetWorkKit
//
//  Created by founder on 14-7-27.
//  Copyright (c) 2014年 com.founder. All rights reserved.
//

#import "FMSNetWorkModule.h"
#import "FMSMKNetworkOperation.h"
#import "FMSMKNetworkEngine.h"
#import "ApplicationUtils.h"
#define WRShopNetWork_NO_NetWork        @"无网络连接"
#define WRShopNetWork_NetWork_Exception @"网络数据异常"
#define WRShopNetWork_NetWork_Error     @"服务器异常"
@interface FMSNetWorkModule()

@property(nonatomic,strong) FMSMKNetworkEngine*    me;

@end

static FMSNetWorkModule*    singleInstance = nil;

@implementation FMSNetWorkModule

+(FMSNetWorkModule* )sharedInstance {
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        NSString  *plistPath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
        NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
        NSString *ip_host = [dataDict objectForKey:@"ip_host"];
//        NSString *ip_root = [dataDict objectForKey:@"ip_root"];
//        NSString *ip_hp = [NSString stringWithFormat:@"%@%@",ip_host,ip_root];
        singleInstance = [[self alloc] initWithHost:ip_host];
    });
    return singleInstance;
}

-(id)initWithHost:(NSString*)hostName {
    self = [super init];
    if(self != nil) {
        _me = [[FMSMKNetworkEngine alloc] initWithHostName:hostName customHeaderFields:nil];
        [_me useCache];
//        [UIImageView setDefaultEngine:_me];
    }
    return self;
}

#pragma mark - 网络接口处理

//GET请求处理的方法
-(void)getRequestDataWithMethod:(NSString*)getStr
                   showHintView:(UIView*)hintView
                   completionCB:(PEBlockCompletion)completionBlock
                        errorCB:(PEBlockError)errorBlock {
    if ([self connectedToNetWork]) {
        [self doGetRequestDataWithMethod:getStr showHintView:hintView completionCB:completionBlock errorCB:errorBlock];
    } else {
        [ApplicationUtils promptFailWithTitle:WRShopNetWork_NO_NetWork showView:hintView];
        errorBlock(WRShopNetWork_NO_NetWork);
    }
}


//POST请求处理的方法
-(void)postRequestDataWithMethod:(NSDictionary*)postDic
                      withURLPath:(NSString*)path
                    showHintView:(UIView*)hintView
                    completionCB:(PEBlockCompletion)completionBlock
                         errorCB:(PEBlockError)errorBlock {
    if ([self connectedToNetWork]) {
        [self doPostRequestDataWithMethod:postDic withURLPath:path showHintView:hintView completionCB:completionBlock errorCB:errorBlock];
    } else {
        [ApplicationUtils promptFailWithTitle:WRShopNetWork_NO_NetWork showView:hintView];
        errorBlock(WRShopNetWork_NO_NetWork);
    }
}

//所有GET请求都会调用这个方法
-(void)doGetRequestDataWithMethod:(NSString*)getStr
                     showHintView:(UIView*)hintView
                      completionCB:(PEBlockCompletion)completionBlock
                           errorCB:(PEBlockError)errorBlock {
    [ApplicationUtils promptRotateWithViewTitle:@"加载中" showView:hintView];
//    _me = [[FMSMKNetworkEngine alloc] initWithHostName:IP_HOST];
    FMSMKNetworkOperation *op = [_me operationWithPath:getStr params:nil httpMethod:@"GET"];
    [op addCompletionHandler:^(FMSMKNetworkOperation *completedOperation) {
        [self completionShowHintView:hintView completedOperation:completedOperation completionCB:^(id result) {
            completionBlock(result);
            return ;
        } errorCB:^(NSString *error) {
            errorBlock(error);
            return ;
        }];
        
    } errorHandler:^(FMSMKNetworkOperation *completedOperation, NSError *error) {
        [ApplicationUtils promptFailWithTitle:WRShopNetWork_NetWork_Error showView:hintView];
        errorBlock(WRShopNetWork_NetWork_Error);
    }];
    [_me enqueueOperation:op];
}


//所有post请求都会调用这个方法
-(void)doPostRequestDataWithMethod:(NSDictionary*)postDic
                    withURLPath:(NSString*)path
                     showHintView:(UIView*)hintView
                     completionCB:(PEBlockCompletion)completionBlock
                           errorCB:(PEBlockError)errorBlock {
    if (hintView) {
        [ApplicationUtils promptRotateWithViewTitle:@"加载中" showView:hintView];
    }
    
//    NSString* post = [self genPostDataWithMethod:postDic withMethod:method];
//    FMSMKNetworkEngine *myEngine = [[FMSMKNetworkEngine alloc] initWithHostName:path];
    FMSMKNetworkOperation *op = [_me operationWithPath:path params:postDic httpMethod:@"POST"];
//    [op setCustomPostDataEncodingHandler:^NSString *(NSDictionary *dataDict) {
//        NSError *error = nil;
//        NSData *data = [NSJSONSerialization dataWithJSONObject:postDic
//                                                       options:0 // non-pretty printing
//                                                         error:&error];
//        if(error)
//            DLog(@"JSON Parsing Error: %@", error);
//        NSString *post = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//        return post;
//    } forType:@"text/json"];
    NSString *filePath = [postDic objectForKey:@"resultContent"];
    [op addFile:filePath forKey:@"answer" mimeType:@"application/x-zip-compressed"];
    [op addCompletionHandler:^(FMSMKNetworkOperation *completedOperation) {
        
        [self completionShowHintView:hintView completedOperation:completedOperation completionCB:^(id result) {
            completionBlock(result);
            return ;
        } errorCB:^(NSString *error) {
            errorBlock(error);
            return ;
        }];
    } errorHandler:^(FMSMKNetworkOperation *completedOperation, NSError *error) {
        [ApplicationUtils promptFailWithTitle:WRShopNetWork_NetWork_Error showView:hintView];
        errorBlock(WRShopNetWork_NetWork_Error);
        return ;
    }];
    [_me enqueueOperation:op];
}
- (void)completionShowHintView:(UIView*)hintView
            completedOperation:(FMSMKNetworkOperation*)completedOperation
                  completionCB:(PEBlockCompletion)completionBlock
                       errorCB:(PEBlockError)errorBlock {
    FMSCHBLog(@"response = %@",completedOperation.responseString);
    NSDictionary* dic = [self jsonStringToDictionary:completedOperation.responseString];
    if( dic == nil) {
        [ApplicationUtils promptFailWithTitle:WRShopNetWork_NetWork_Exception showView:hintView];
        errorBlock(WRShopNetWork_NetWork_Exception);
        return ;
    }
    
    NSDictionary* error = [dic objectForKey:@"error"];
    if( error != nil) {
        NSString* errorCode = [error objectForKey:@"errorCode"];
        NSString* errorMsg = [error objectForKey:@"errorMsg"];
        if([errorCode isEqualToString:@"103"]) {
            completionBlock(nil);
            //服务器返回空的情况，某些协议需要保存空数据
            if (hintView) {
                [ApplicationUtils promptRemove];
            }
        } else {
            [ApplicationUtils promptFailWithTitle:errorMsg showView:hintView];
            errorBlock(errorMsg);
        }
        return ;
    }
    
    NSMutableDictionary*   data = (NSMutableDictionary*)[dic mutableCopy];
//    [data removeObjectForKey:@"result"];
    
    if(data == nil) {
        errorBlock(WRShopNetWork_NetWork_Exception);
        [ApplicationUtils promptFailWithTitle:WRShopNetWork_NetWork_Exception showView:hintView];
    } else {
        completionBlock(data);
        [ApplicationUtils promptRemove];
    }
    return ;
}

#pragma mark - json handle
-(NSString*)genPostDataWithMethod:(NSDictionary*)data withMethod:(NSString*)method {
    NSString* dataString = [data jsonEncodedKeyValueString];
    NSString* retString = [NSString stringWithFormat:@"{\"method\":\"%@\",\"data\":%@}",method,dataString];
    return retString;
}

-(id) jsonStringToDictionary:(NSString *)jsonString {
    if ([jsonString length]==0) {
        FMSCHBLog(@"!****error jsonStringToDictionary is zero******!");
        return nil;
    }
    NSError *errorDes = nil;
    id returnValue = [NSClassFromString(@"NSJSONSerialization") JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&errorDes];
    if(errorDes) {
        FMSCHBLog(@"JSON Parsing Error: %@ the original str is %@", errorDes,jsonString);
        return nil;
    }
    return returnValue;
}
#pragma mark - 网络连接的检查
//检查当前网络连接是否正常
-(BOOL)connectedToNetWork{
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    if (!didRetrieveFlags) {
        printf("Error. Count not recover network FMReachability flags\n");
        return NO;
    }
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    return (isReachable && !needsConnection) ? YES : NO;
}

#pragma mark - 下载处理
-(FMSMKNetworkOperation*) downloadFatAssFileFrom:(NSString*) remoteURL toFile:(NSString*) filePath  completionCB:(PEBlockCompletion)completionBlock{
    
    FMSMKNetworkOperation *op = [_me operationWithURLString:remoteURL
                                                   params:nil
                                               httpMethod:@"GET"];
    
    [op addDownloadStream:[NSOutputStream outputStreamToFileAtPath:filePath
                                                            append:YES]];
//cui  mark
//    [op onDownloadProgressChanged:^(double progress) {
//        NSLog(@"onDownloadProgressChanged------%f",progress);
//        if (progress == 1.0f) {
//            completionBlock(nil);
//        }
//    }]; //下载进度
    [op addCompletionHandler:^(FMSMKNetworkOperation* completedRequest) {
        FMSCHBLog(@"download file finished!");
        completionBlock(nil);
    }  errorHandler:^(FMSMKNetworkOperation *errorOp, NSError* err) {
        FMSCHBLog(@"download file error: %@", err);
        completionBlock(err);
    }];
    [_me enqueueOperation:op];
    return op;
}

#pragma mark - 上传处理
-(FMSMKNetworkOperation*) uploadImageFromFile:(NSString*) file
                              completionCB:(PEBlockCompletion)completionBlock
                                   errorCB:(PEBlockError)errorBlock {
    
    FMSMKNetworkOperation *op = [_me operationWithPath:@"api/upload"
                                              params:[NSDictionary dictionaryWithObjectsAndKeys:
                                                      @"", @"username",
                                                      @"", @"password",
                                                      nil]
                                          httpMethod:@"POST"];
    
    [op addFile:file forKey:@"media"];
    
    //设置冻结处理
    [op setFreezable:YES];
    
    [op addCompletionHandler:^(FMSMKNetworkOperation *completedOperation) {
        NSString *xmlString = [completedOperation responseString];
        NSUInteger start = [xmlString rangeOfString:@"<mediaurl>"].location;
        if(start == NSNotFound) {
            
            DLog(@"%@", xmlString);
            errorBlock(nil);
            return;
        }
        xmlString = [xmlString substringFromIndex:start + @"<mediaurl>".length];
        NSUInteger end = [xmlString rangeOfString:@"</mediaurl>"].location;
        xmlString = [xmlString substringToIndex:end];
        completionBlock(xmlString);
    } errorHandler:^(FMSMKNetworkOperation *completedOperation, NSError *error) {
        errorBlock([errorBlock localizedDescription]);
    }];
    
    [_me enqueueOperation:op];
    
    
    return op;
}
/*
#pragma mark - 缩略图
-(void) imagesForTag:(NSString*)tag completionCB:(PEBlockCompletion)completionBlock errorCB:(PEBlockError)errorBlock {
    FMSMKNetworkOperation *op = [_me operationWithPath:tag];
    
    [op addCompletionHandler:^(FMSMKNetworkOperation *completedOperation) {
//        [completedOperation ima
        NSLog(@"response = %@",completedOperation);
        completionBlock(nil);
    } errorHandler:^(FMSMKNetworkOperation *completedOperation, NSError *error) {
        NSLog(@"error = %@",completedOperation);
        errorBlock(@"");
    }];
    
//    [op onCompletion:^(FMSMKNetworkOperation *completedOperation) {
//        
//        NSDictionary *response = [completedOperation responseJSON];
//        imageURLBlock([[response objectForKey:@"photos"] objectForKey:@"photo"]);
//        
//    } onError:^(NSError *error) {
//        
//        errorBlock(error);
//    }];
    
    [_me enqueueOperation:op];
}
*/
-(void)cancleAllOperation{
    if (_me) {
        [_me cancelAllOperations];
    }
}
@end
